from django.core.cache import cache
from django.http import HttpResponse
from django.core.context_processors import request
from django.shortcuts import render_to_response
from django import forms
from django.utils import simplejson
from jrcmodel.models import JrcParameter, JrcSystem
from tracking.models import TrackRecordForex, TrackRecordFutures

class KeyIntegrityViewForm(forms.Form):
    table_name = forms.CharField(max_length = 128)
    total_records = forms.IntegerField()
    key_missed_total = forms.IntegerField()
    key_proceed = forms.IntegerField()

def check_key_integrity(request, table):
    return render_to_response("maintain/checkintegrity.html", {"table_name": table})

def clear_cache(request):
    """
    Clears all cached objects for ITTC
    """
    cache.clear()
    TrackRecordForex.clear_tracks_cache()
    # Interested in CST and Market cache, so year and month are not important
    TrackRecordFutures.clear_tracks_cache(2012, 1)
    return HttpResponse("Cache is cleared. <a href='javascript:history.go(-1);'>Back</a>")

def get_record_count(request, table):
#    print "Table to count is %s..." % table
    total = 0
    if table == "parameter":
        total = JrcParameter.objects.all().count()
    elif table == "system":
        total = JrcSystem.objects.all().count()
    
    return HttpResponse(simplejson.dumps({"Total": total}), mimetype = "appcication/json")

def get_missed_keys(request, table, offset):
    # how many records check
    limit = 100
    print "Check missed keys in %s. Offset it %s..." % (table, offset)

    offset = int(offset)

    missed = 0
    proceed = 0

#    qs = JrcParameter.objects.all().order_by("id")[:offset:limit]
    if table == "parameter":
        qs = JrcParameter.objects.all()
    elif table == "system":
        qs = JrcSystem.objects.all()

    qs = qs.order_by("id")[:limit:offset]

    
    key = offset + 1
    missed_keys = []

    for item in qs:
        print item
        if item.pk > 0:
            # Found missed key
            if key != item.jrc_key:
                # Add every missed key
                for m in range(key - 1, item.pk):
                    missed_keys.append(m)
                key = item.pk

            key += 1
            proceed += 1
        else:
            print "Empty queryset!"

    print missed_keys
#    proceed = len(qs)
    missed = len(missed_keys)

    return HttpResponse(simplejson.dumps({"TotalMissed": missed, "Proceed": proceed, "Missed": missed_keys}), mimetype = "application/json")
    #return HttpResponse(simplejson.dumps({"TotalMissed": missed, "Proceed": proceed}))
